import Vue from 'vue';
import Md5 from 'crypto-js/md5.js';
import CryptoJS from 'crypto-js';

const utils = new Vue({
  data() {
    return {
      appkey: 'sfowefnn23nf93nv',
      appsecret: 'OkilCMKLyjo2cXLgDDBq1da39R0fPIeb'
    }
  },
  methods: {

    // returnData: function (Arr,appid,app_secret) {
    //   this.appkey=appid;
    //   this.appsecret=app_secret;
    //   Arr['ts'] = Date.parse(new Date());
    //   var BArr = {};
    //   for (var i in Arr) {
    //     if(Arr[i] === true) {
    //       BArr[i] = 1;
    //     }else if(Arr[i] === false){
    //       BArr[i] = 0;
    //     }else if(Arr[i] === null){
    //       BArr[i] = '';
    //     }else{
    //       BArr[i] = Arr[i];
    //     }
        
    //   }
    
    //   var sig = this.getSign(Arr);
    //   var AesStr = this.aesEncrypt(BArr, sig);

    //   var JsonObj = {};
    //   JsonObj['sig'] = sig;
    //   JsonObj['data'] = AesStr;

    //   return JsonObj;
    // },

    returnData: function (Arr,appkey=null,appsecret=null) {

      Arr['ts'] = Date.parse(new Date());
      var BArr = {};
      for (var i in Arr) {
        if(Arr[i] === true) {
          BArr[i] = 1;
        }else if(Arr[i] === false){
          BArr[i] = 0;
        }else if(Arr[i] === null){
          BArr[i] = '';
        }else{
          BArr[i] = Arr[i];
        }
        
      }
    
      var sig = this.getSign(Arr,appkey,appsecret);
      var AesStr = this.aesEncrypt(BArr, sig);

      var JsonObj = {};
      JsonObj['sig'] = sig;
      JsonObj['data'] = AesStr;

      return JsonObj;
    },

    //生成签名sign
    getSign: function (Arr,appkey=null,appsecret=null) {
      Arr.appkey = appkey ? appkey : process.env.VUE_APP_APPKEY;
      Arr.appsecret = appsecret ? appsecret : process.env.VUE_APP_APPSECRET;
      var newArr = this.sortList(Arr)

      var jsonStr = JSON.stringify(newArr);
      // console.log(jsonStr,newArr,Arr)
      var md5Str = Md5(jsonStr + Arr.appsecret).toString();
      var str = Md5(md5Str + Arr.appkey).toString();
      return str;

    },
    //aes加密
    aesEncrypt: function (Arr, sign) {
      var key = sign.substring(0, 8) + sign.substring(16, 24);
      var iv = sign.substring(8, 16) + sign.substring(24, 32);
      var data = JSON.stringify(Arr);



      var encrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(iv),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
      });
      return encrypted.toString();
    },
    //字典排序
    sortList: function (Arr) {
      
      var obj = JSON.parse(JSON.stringify(Arr));

      // console.log(Arr,obj)
      var indexArr = [];
      for (var i in obj) {
        if(obj[i] instanceof Object) {
           continue;
        }else if(obj[i] instanceof Array) {
            continue;
        }else{
           indexArr.push(i);
        }

      }


      indexArr.sort();
      var newArr = {};
      for (var j in indexArr) {
        for (var i in obj) {
          if (indexArr[j] == i) {
            newArr[indexArr[j]] = this._urlencode(obj[indexArr[j]]);
          }
        }
      }
      // console.log(newArr,obj)
      return newArr;
    },
    //aes解密
    aesDecrypt: function (Str, sign) {
      var key = sign.substring(0, 8) + sign.substring(16, 24);
      var iv = sign.substring(8, 16) + sign.substring(24, 32);


      var decrypted = CryptoJS.AES.decrypt(decodeURIComponent(Str), CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(iv),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
      });

      var plaintext = decrypted.toString(CryptoJS.enc.Utf8); //WordArray对象转utf8字符串

      if (plaintext.substring(0, 1) == '{') {
        return JSON.parse(plaintext.substring(0, (plaintext.lastIndexOf('}') + 1)));
      } else {
        return JSON.parse(plaintext.substring(0, (plaintext.lastIndexOf(']') + 1)));
      }
    },
    cacheSet: function (name, data) {
      var _data = data || {};
      if (typeof _data == 'string') {
        _data = {
          localStorageNames: data
        };
      }
      var _name = Md5(name).toString();
      window.localStorage.setItem(_name, this.aesEncrypt(_data, _name));
      return true;
    },
    cacheGet: function (name) {
      var _name = Md5(name).toString();
      var value = window.localStorage.getItem(_name);
      if (value == null) {
        return value;
      }
      var _json = this.aesDecrypt(value, _name);
      var str = _json.localStorageNames || null
      if (str != null) {
        return str;
      }
      return _json;
    },
    cacheRemove: function (name) {
      var _name = Md5(name).toString();
      window.localStorage.removeItem(_name);
      return true;
    },
    cacheClear: function () {
      window.localStorage.clear();
    },

    getUrlParam: function (url, data, event = true) {
      var paramArr = {};
      if (!url) {
        return false;
      }
      var arrObj = url.replace(new RegExp('.html', 'g'), '').split("?");

      if (arrObj.length > 1) {
        var arrPara = arrObj[1].split("&");
        var arr;

        for (var i = 0; i < arrPara.length; i++) {
          arr = arrPara[i].split("=");
          if (arr[0]) {
            if (event) {
              if (arr[1] == '###') {
                var param = [];
                for (var j in data) {
                  param.push(data[j][arr[0]]);
                }
              } else {
                var param = arr[1];
              }

              paramArr[arr[0]] = param;
            } else {
              if (arr[1] == '###') {
                for (var j in data) {
                  paramArr[arr[0]] = data[arr[0]];
                  break;
                }
              } else {
                paramArr[arr[0]] = arr[1];
              }
            }
          }
        }

        var obj = {};
        if (arrObj[0].substring(0, 1) == '/') {
          obj.path = arrObj[0];
        } else {
          obj.path = '/' + arrObj[0];
        }
        obj.query = paramArr;
        return obj;
      }

      var obj = {};

      if (url.substring(0, 1) == '/') {
        obj.path = url;
      } else {
        obj.path = '/' + url;
      }

      obj.query = {};
      return obj;
    },

    //笛卡尔积算法
    descartes: function (array) {

      if (array.length < 2) return array[0] || [];
      return [].reduce.call(array, function (col, set) {
        var res = [];
        col.forEach(function (c) {
          set.forEach(function (s) {
            var t = [].concat(Array.isArray(c) ? c : [c]);
            t.push(s);
            res.push(t);
          })
        });
        return res;
      });
    },
    //图片转base64
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    /**
     * 将以base64的图片url数据转换为Blob
     * @param urlData
     *            用url方式表示的base64图片数据
     */
    convertBase64UrlToBlob(urlData) {

      var bytes = window.atob(urlData.split(',')[1]); //去掉url的头，并转换为byte

      //处理异常,将ascii码小于0的转换为大于0
      var ab = new ArrayBuffer(bytes.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }

      return new Blob([ab], {
        type: 'image/png'
      });
    },
    //计算两个日期相差的天数
    getDaysBetween(day_one, day_tow) {
      var startDate = Date.parse(day_one);
      var endDate = Date.parse(day_tow);
      var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);

      return Math.abs(days);
    },
    _urlencode(str){
   
      var newstr = encodeURIComponent(str);
      newstr = newstr.replace(/\%20/g,'+');
      newstr = newstr.replace(/\!/g,'%21');
      newstr = newstr.replace(/\(/g,'%28');
      newstr =newstr.replace(/\*/g,'%2A');
      newstr =newstr.replace(/\(/g,'%28');
      newstr =newstr.replace(/\)/g,'%29');
      newstr =newstr.replace(/\'/g,'%27');
      newstr =newstr.replace(/\~/g,'%7E');
      newstr = this._replace(newstr);
     
      return newstr;
    },
    _replace(newstr){
      
      newstr =newstr.replace(/null/g,'');
      newstr =newstr.replace(/true/g,1);
      newstr =newstr.replace(/false/g,0);
      return newstr;
    }

  }

});

export {
  utils
}
